package com.hystrix;

import com.hystrix.command.IsolationCommand;
import com.netflix.config.ConfigurationManager;
import com.netflix.hystrix.HystrixCommandProperties;

import java.util.concurrent.CompletableFuture;

/**
 * 请先启动当前项目的Spirng Boot
 * Created by earl on 2018/5/1.
 */
public class TestIsolation {


    public static void main(String [] args) throws InterruptedException {
//        testThread();
        tetsSemaphore();
    }

    //测试线程隔离策略
    private static void testThread() throws InterruptedException {
        // 配置线程池大小为3
        ConfigurationManager.getConfigInstance().setProperty(
                "hystrix.threadpool.default.coreSize", 3);
        //由于执行命令次数大于线程池大小，进行6次循环，将会有三次回退
        for(int i = 0; i < 6; i++) {
            IsolationCommand c = new IsolationCommand(i);
            c.queue();
        }
        Thread.sleep(5000);

    }


    //信号量隔离策略
    public static void  tetsSemaphore() throws InterruptedException {
        // 配置使用信号量的策略进行隔离
        ConfigurationManager.getConfigInstance().setProperty(
                "hystrix.command.default.execution.isolation.strategy",
                HystrixCommandProperties.ExecutionIsolationStrategy.SEMAPHORE);
        // 设置最大并发数，默认值为10,现在是2
        ConfigurationManager
                .getConfigInstance()
                .setProperty(
                        "hystrix.command.default.execution.isolation.semaphore.maxConcurrentRequests",
                        2);
        // 设置执行回退方法的最大并发，默认值为10
        ConfigurationManager
                .getConfigInstance()
                .setProperty(
                        "hystrix.command.default.fallback.isolation.semaphore.maxConcurrentRequests",
                        20);
        for (int i = 0; i < 20; i++) {
            final int index = i;
            CompletableFuture.supplyAsync(() -> {
                IsolationCommand c = new IsolationCommand(index);
                return c.execute();

            });
        }
        Thread.sleep(5000);
    }





}
